<?php
/**
* 上传类
* @author 江羿平<jyp@cjkt.com>
*/
namespace Libraries;
class Uploader{

	/**
	 * 上传图片
	 * @param   string  $field  上传表单名称
	 * @return  string | bool
	 */
	public static function image($field = 'file'){
		$file = self::upload($field,'uploadfiles/image/');
		if($file){
			return $file;
		}else{
			return false;
		}
	}

	/**
	* 上传文件
	* @param   string  $field  上传表单名称
	* @return  string | bool
	*/
	public static function file($field = 'file'){
		$file = self::upload($field,'uploadfiles/file/');
		if($file){
			return '/file/'.$file;
		}else{
			return false;
		}
	}

	/**
	 * 上传头像
	 * @param   string  $field  上传表单名称
	 * @return  string | bool
	 */
	public static function avatar($field = 'file'){
		$file =  self::upload($field,'uploadfiles/avatar/');
		if($file){
			self::image_resize('uploadfiles/avatar/'.$file);
		}
		return $file;
	}

	/**
	 * @param   string  $field  上传表单名称
	 * @param   string  $base_path  文件上传路劲
	 * @return  string | bool
	 */
	public static function upload($field='file',$base_path = 'uploadfiles/'){
		$config = CONFIG('upload');
		$config = $config['upload'];
		if($base_path == 'uploadfiles/file/'){
			$config['allowed_types'] = 'mp4|doc|docx|ppt|pptx|xlsx|xls|txt|rar|zip';
		}
		$config['base_path'] = $base_path;
		$config['upload_path'] = $config['base_path'].$config['sub_path'];
		if(!is_dir($config['upload_path'])){
			//var_dump($config['upload_path']);
			mkdir($config['upload_path'],0777,TRUE);
		}
		$CI =& get_instance();
        $CI->load->library('upload', $config);
        if (!$CI->upload->do_upload($field)) {
          // $a = $CI->upload->display_errors('<p>', '</p>');
          // echo $a;
           return FALSE;
        }
        $upload_data = $CI->upload->data();
        $file = $config['sub_path'] . $upload_data['file_name'];

        //oss($file,$config['upload_path'].$upload_data['file_name']);
        return $file;
	}

	/**
	 * base64方式上传
	 * @param string  $base64_content 上传文件内容
	 * @param string  $path  文件保存路劲
	 * @param string  $ext   文件后缀名
	 */
	public static function base64_up($base64_content,$path,$ext){
		$path = realpath($path).'/';
        $year = date('Y',time());
        $md = date('md',time());
        if(!is_dir($path.$year)) mkdir($path.$year);
        if(!is_dir($path.$year.'/'.$md)) mkdir($path.$year.'/'.$md);

        $data =  str_replace('[removed]', '', $base64_content);
        $filename = $year.'/'.$md.'/'.md5(time()).'.'.$ext;
        $new_file = $path.$filename;

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_content, $result)){
		  $type = $result[2];
		  $filename = $year.'/'.$md.'/'.md5(time()).'.png';
		  $new_file = $path.$filename;
		  if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_content)))){
		     if(strpos($path, 'avatar')) self::image_resize($new_file);
		     return $filename;
		  }
		  return false;
		}

        if (file_put_contents($new_file, base64_decode($data))){
            if(strpos($path, 'avatar'))  self::image_resize($new_file);
            return $filename;
        }
        return false;
    }

    /**
     * 剪切图片
     * @param string $image_name
     * @return void
     */
    public static function image_resize($image_name,$width = 110,$height=110) {
    	$CI = & get_instance();
        $CI->load->library('image_lib');

        $config['image_library'] = 'gd2';//选择图像库，还可以选ImageMagick
        $config['source_image'] = $image_name;
        //当 maintain_ratio 选项设为可用时，生成的缩略图将在保持纵横比例的同时，尽可能的在宽度和高度上接近所设定的width和height
        $config['maintain_ratio']  = TRUE;
        $config['width'] = $width;
        $config['height'] = $height;
        $config['create_thumb'] = TRUE;//是否生成缩略图
        $config['thumb_marker']='';
        $CI->image_lib->initialize($config);
        $CI->image_lib->resize();
    }

    /**
     * 保存远程图片
     * @param string $url 图片链接
     * @param string $path 存储路径
     * @param string $filename 存储名称
     * @return  bool|integer 成功返回TRUE 失败返回错误码
     */
    public static function curl_save($url , $path , $filename){
    	$ch = curl_init();
    	$fp = fopen($path.$filename,'wb');
    	if(!$fp){
    		return -1;
    	}
    	$path = realpath($path).'/';
        $year = date('Y',time());
        $md = date('md',time());
        if(!is_dir($path.$year)) mkdir($path.$year);
        if(!is_dir($path.$year.'/'.$md)) mkdir($path.$year.'/'.$md);
        $filename = $year.'/'.$md.'/'.$filename;
    	curl_setopt($ch,CURLOPT_URL,$url);
    	curl_setopt($ch,CURLOPT_FILE,$fp);
    	curl_setopt($ch,CURLOPT_TIMEOUT,20);
    	$res = curl_exec($ch);
    	curl_close($ch);
    	fclose($fp);
    	if($res){
    		return $filename;
    	} else{
    		return -2;
    	}
    }
}
?>
